package com.example.myapplication.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.myapplication.R;
import com.example.myapplication.entity.Message;

import java.util.List;

public class MessageListAdapter extends BaseAdapter {

    private List<Message> messageList; // 数据源
    private LayoutInflater inflater; // 布局装载器
    private Context context;

    public MessageListAdapter(Context context, List<Message> messageList) {
        this.messageList = messageList;
        this.inflater = LayoutInflater.from(context);
        this.context = context;
    }

    // 需要显示的数据数量
    @Override
    public int getCount() {
        return this.messageList.size();
    }

    // 指定的索引对应的数据项
    @Override
    public Object getItem(int position) {
        return this.messageList.get(position);
    }

    // 制定的索引对应的数据项ID
    @Override
    public long getItemId(int position) {
        return position;
    }

    // 返回每一项的显示内容
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        //如果view未被实例化过，缓存池中没有对应的缓存
        if (convertView == null) {
            viewHolder = new ViewHolder();
            //由于我们只需要将XML转化为view，并不涉及具体布局，所以第二个参数通常设置为null
            convertView = inflater.inflate(R.layout.item_message_list,null);

            //对viewHolder的属性赋值
            viewHolder.who = (TextView) convertView.findViewById(R.id.tv_who);
            viewHolder.latestMessage = (TextView) convertView.findViewById(R.id.tv_latest_message);
            viewHolder.time = (TextView) convertView.findViewById(R.id.tv_time);
            viewHolder.portrait = (ImageView) convertView.findViewById(R.id.iv_portrait);

            //通过setTag将converView与viewHolder关联
            convertView.setTag(viewHolder);
        } else { //如果缓存池中有对应的view缓存，则直接通过getTag取出viewHolder
            viewHolder = (ViewHolder) convertView.getTag();
        }

        //取出String对象
        Message message = messageList.get(position);

        //设置控件的数据
        viewHolder.who.setText(message.getUserName());
        viewHolder.latestMessage.setText(message.getLatestMessage());
        viewHolder.time.setText(message.getTime());
        int portraitResId = context.getResources().getIdentifier(message.getPortrait(), "drawable", context.getPackageName());
        viewHolder.portrait.setImageResource(portraitResId);

        return convertView;
    }

    //ViewHolder用于缓存控件，属性分别对应item布局文件的控件
    class ViewHolder {
        public TextView who;
        public TextView latestMessage;
        public TextView time;
        public ImageView portrait;
    }
}
